<?php
declare(strict_types=1);

namespace App\Model;



use Hyperf\Database\Model\Events\Saving;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Database\Model\SoftDeletes;
use League\Flysystem\Filesystem;
use Hyperf\Di\Annotation\Inject;
/**
 * @property $id
 * @property $name
 * @property $created_at
 * @property $updated_at
 */
class Product extends Model
{
    use SoftDeletes;

     /**
     * @var Filesystem
     */
    #[Inject]
    private Filesystem $filesystem;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected? string $table = 'products';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected array $fillable = ['id', 'name', 'price', 'category_id', 'width', 'height', 'dpi', 'thumb', 'attrs', 'skus', 'detail', 'created_at', 'updated_at'];
    protected array $hidden = ['created_at', 'updated_at', 'deleted_at'];
    protected array $casts = ['attrs' => 'array', 'skus' => 'array', 'thumb'=> 'array'];
    
    protected array $appends = ['thumbs'];
    public function category(){
        return $this->hasOne(Category::class,'id','category_id');
    }

    public function layouts(){
        return $this->hasMany(ProductLayout::class, 'product_id' ,'id')->orderBy('id');
    }

    public function getThumbsAttribute(){
        if(empty($this->thumb))return [];
        return array_map(function($item){
            if(strstr($item, 'http')) {
                return $item;
            } else {
                return $this->filesystem->publicUrl($item);
            }
        }, $this->thumb);
    }
}